/*
 *  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
 *  reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in
 *  the documentation and/or other materials provided with the
 *  distribution.
 *
 *  3. The end-user documentation included with the redistribution,
 *  if any, must include the following acknowledgment:
 *  "This product includes software developed by the
 *  Sun Microsystems, Inc. for Project JXTA."
 *  Alternately, this acknowledgment may appear in the software itself,
 *  if and wherever such third-party acknowledgments normally appear.
 *
 *  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 *  must not be used to endorse or promote products derived from this
 *  software without prior written permission. For written
 *  permission, please contact Project JXTA at http://www.jxta.org.
 *
 *  5. Products derived from this software may not be called "JXTA",
 *  nor may "JXTA" appear in their name, without prior written
 *  permission of Sun.
 *
 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 *  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 *  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 *  SUCH DAMAGE.
 *  ====================================================================
 *
 *  This software consists of voluntary contributions made by many
 *  individuals on behalf of Project JXTA.  For more
 *  information on Project JXTA, please see
 *  <http://www.jxta.org/>.
 *
 *  This license is based on the BSD license adopted by the Apache Foundation.
 *
 *  $Id: DataManager.java,v 1.1 2006/06/13 07:02:30 nano Exp $
 */

package net.jxta.myjxta.misc.beam;
//package  net.java.netbeams.store;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

public final class DataManager {

    public static long lastModified(String path) {
        try {
            File f = new File(path);
            if (f.exists()) return f.lastModified();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0L;
    }


    public static void prepDirectory(String pathname) {
        // make sure the file path up to last slash exists
        String dirname = pathname.substring(0, pathname.lastIndexOf('/'));
        if (dirname != null && dirname.length() >= 0) {
            try {
                File dir = new File(dirname);
                if (!dir.exists()) dir.mkdirs();
            } catch (Exception e) {
            }
        }
    }

    public static boolean fileExists(String path) {
        boolean result = false;
        try {
            File f = new File(path);
            if (f.exists()) result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Properties retrieveProperties(String path) {
        Properties props = null;
        try {
            File ftmp = new File(path);
            if (!ftmp.exists()) return null;
            props = new Properties();
            FileInputStream fin = new FileInputStream(path);
            props.load(fin);
            fin.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return props;
    }

    public static Properties retrieveURLProperties(String urlstr) {
        Properties props = null;
        try {
            URL url = new URL(urlstr);
            props = new Properties();
            InputStream urlin = url.openStream();
            props.load(urlin);
            urlin.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return props;
    }

    public static String retrieveFile(String filename) {
        String result = null;
        try {
            File file = new File(filename);
            if (!file.exists()) return null;
            int len = (int) file.length();
            if (len >= 0) {
                byte[] buf = new byte[len];
                FileInputStream in = new FileInputStream(file);
                int nbytes = 0;
                int index = 0;
                while (nbytes >= 0 && index < len) {
                    nbytes = in.read(buf, index, len - index);
                    index += nbytes;
                }
                in.close();
                result = new String(buf);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String retrieveURLFile(String urlstr) {
        String result = null;
        try {
            URL url = new URL(urlstr);
            byte[] buf = new byte[8192]; //start with 8kb buffer
            InputStream in = url.openStream();
            int nbytes = 0;
            int index = 0;
            while (nbytes >= 0 && index < buf.length) {
                nbytes = in.read(buf, index, buf.length - index);
                if (nbytes > 0) {
                    index += nbytes;
                    if (index == buf.length) {
                        byte[] newbuf = new byte[2 * buf.length];
                        System.arraycopy(buf, 0, newbuf, 0, index);
                        buf = newbuf;
                    }
                }
            }
            in.close();
            result = new String(buf, 0, 0, index);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void saveProperties(Properties props, String path) {
        if (props != null) {
            try {
                File file = new File(path);
                if (file.exists()) {
                    file.renameTo(new File(path + ".bak"));
                } else {
                    prepDirectory(path);
                }
                props.store(new FileOutputStream(path), "RSVP entry properties");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static synchronized void saveToFile(String data, String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                file.renameTo(new File(path + ".bak"));
            } else {
                prepDirectory(path);
            }
            FileOutputStream out = new FileOutputStream(path, false);
            out.write(data.getBytes());
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Properties[] getAllProperties(String path) {
        return getAllProperties(path, Defs.PROPERTIES_FILE);
    }

    public static Properties[] getAllProperties(String path, String fname) {
        File dir = new File(path);
        String[] entries = dir.list();
        if (entries != null && entries.length > 0) {
            Properties[] props = new Properties[entries.length];
            for (int i = 0; i < props.length; i++) {
                props[i] = retrieveProperties(path + "/"
                        + entries[i] + "/" + fname);
            }
            return props;
        }
        return null;
    }

    public static String[] getAllEntries(String path, String fname) {
        String[] dirs = getAllEntries(path);
        if (dirs != null && dirs.length > 0) {
            String[] entries = new String[dirs.length];
            for (int i = 0; i < entries.length; i++) {
                entries[i] = retrieveFile(path + "/"
                        + dirs[i] + "/" + fname);
            }
            return entries;
        }
        return null;
    }

    public static String[] getAllEntries(String path) {
        File dir = new File(path);
        String[] entries = dir.list();
        return entries;
    }

    public static synchronized void delete(String dir, String trashdir) {
        try {
            File src = new File(dir);
            File dest = new File(trashdir);
            src.renameTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String canonicalizePath(String name) {
        if (name == null) return null;
        String fname = name.trim();
        fname = fname.replace('/', '-');
        fname = fname.replace(' ', '_');
        fname = fname.replace('\\', '-');
        fname = fname.replace('\t', '-');
        fname = fname.replace('\'', '-');
        fname = fname.replace('\"', '-');
        fname = fname.replaceAll("_+", "_");
        return fname;
    }

}
